//
//  CYBindPhoneViewController.m
//  cyydt
//
//  Created by chu on 2019/2/3.
//  Copyright © 2019 chu. All rights reserved.
//

#import "CYBindPhoneViewController.h"

@interface CYBindPhoneViewController ()<UITextFieldDelegate>
{
    BOOL _canGetCode;
    NSInteger _countDown;
    NSTimer *_timer;
}
@end

@implementation CYBindPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"绑定手机号";
    _countDown = 60;
    self.phoneTF.delegate = self;
    self.codeTF.delegate = self;
    self.bindBtn.layer.masksToBounds = YES;
    self.bindBtn.layer.cornerRadius = self.bindBtn.frame.size.height / 2;
    self.view.backgroundColor = [UIColor whiteColor];
}

- (IBAction)codeAction:(UIButton *)sender {
    if (_canGetCode) {
        [self getVerify];
    }
}

- (IBAction)bindAction:(UIButton *)sender {
    [EasyShowLodingView showLoding];
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"user/giveUserPhone"];
    NSDictionary *param = @{@"phone":self.phoneTF.text, @"captcha":self.codeTF.text};
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 2.设置非校验证书模式
    sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    [sessionManager.securityPolicy setValidatesDomainName:NO];
    
    [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript", nil];
    [sessionManager.requestSerializer setValue:self.token forHTTPHeaderField:@"usertoken"];

    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    [sessionManager POST:str parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [EasyShowLodingView hidenLoding];

        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            if ([resultDic[Response_code] integerValue] == Response_value) {
                [self getUserInfosWithToken:self.token];
            }else{
                [self.view makeToast:resultDic[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EasyShowLodingView hidenLoding];

    }];
}

#pragma mark - 获取用户信息
- (void)getUserInfosWithToken:(NSString *)token{
    [EasyShowLodingView showLoding];

    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"userInfo"];
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 2.设置非校验证书模式
    sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    [sessionManager.securityPolicy setValidatesDomainName:NO];
    
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/plain",@"image/png", nil];
    [sessionManager.requestSerializer setValue:token forHTTPHeaderField:@"usertoken"];
    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    [sessionManager GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [EasyShowLodingView hidenLoding];

        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            if ([resultDic[Response_code] integerValue] == Response_value) {
                NSDictionary *data = resultDic[@"data"];
                NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:data];
                [muDic setObject:token forKey:@"token"];
                [YLUserInfo getuserInfoWithDic:muDic];
                NSUserDefaults *us = [NSUserDefaults standardUserDefaults];
                [us setObject:self.phoneTF.text forKey:UserPhone];
                [us synchronize];
                [[AppDelegate sharedAppDelegate] popToRootViewController];
            }else{
                
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [EasyShowLodingView hidenLoding];

    }];
}

- (void)getVerify{
    NSString *url = [NSString stringWithFormat:@"%@%@",User_HOST, @"code"];
    NSDictionary *param = @{@"phone":self.phoneTF.text};
    [[XBRequest sharedInstance] getDataWithUrl:url Parameter:param ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"验证码 ---- %@",responseResult);
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            self.codeBtn.enabled = YES;
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                self->_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
                
            }else{
                self.codeBtn.enabled = YES;
                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

#pragma mark - PrivateMethod
- (void)onTimer{
    if (_countDown > 0) {
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%ld秒重新获取", (long)_countDown] forState:UIControlStateNormal];
        _countDown--;
    }else{
        _countDown = 60;
        [_timer invalidate];
        _timer = nil;
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.codeBtn.enabled = YES;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.phoneTF) {
        NSString *resultStr = [self.phoneTF.text stringByReplacingCharactersInRange:range withString:string];
        NSLog(@"resultStr -- %@",resultStr);
        if (resultStr.length == 11) {
            [self yanzhengShouji];
            return YES;
        }
        if (resultStr.length == 12) {
            return NO;
        }
    }
    if (textField == self.codeTF) {
        NSString *resultStr = [self.codeTF.text stringByReplacingCharactersInRange:range withString:string];
        if (resultStr.length > 0) {
            self.bindBtn.backgroundColor = RGBOF(0xF43636);
            [self.bindBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }else {
            self.bindBtn.backgroundColor = RGBOF(0xe3e3e3);
            [self.bindBtn setTitleColor:RGBOF(0x999999) forState:UIControlStateNormal];
        }
    }
    return YES;
}

- (void)yanzhengShouji{
    [EasyShowLodingView showLoding];
    [[XBRequest sharedInstance] getDataWithUrl:[NSString stringWithFormat:@"%@%@",User_HOST, @"checkPhone"] Parameter:@{@"phone":self.phoneTF.text} ResponseObject:^(NSDictionary *responseResult) {
        NSLog(@"验证手机是否绑定 ---- %@",responseResult);
        [EasyShowLodingView hidenLoding];
        if ([responseResult objectForKey:@"resError"]) {
            [self.view makeToast:ResErrorMessage duration:1.5 position:CSToastPositionCenter];
            
        }else{
            if ([responseResult[Response_code] integerValue] == Response_value) {
                self->_canGetCode = YES;
            }else{
                [LEEAlert alert].config
                .LeeHeaderColor([UIColor whiteColor])
                .LeeAddContent(^(UILabel *label) {
                    label.font = [UIFont systemFontOfSize:18];
                    label.textColor = [UIColor blackColor];
                    label.text = @"该手机号已绑定，请换一个手机号";
                }).LeeAddAction(^(LEEAction *action) {
                    action.titleColor = RGBOF(0x666666);
                    action.borderColor = RGBOF(0xE0DFDF);
                    action.title = @"取消";
                    
                })
                .LeeAddAction(^(LEEAction *action) {
                    action.titleColor = RGBOF(0xF43636);
                    action.borderColor = RGBOF(0xE0DFDF);
                    action.title = @"确定";
                    action.clickBlock = ^{
                        
                    };
                })
                .LeeShow();
//                [self.view makeToast:responseResult[Response_Message] duration:1.5 position:CSToastPositionCenter];
            }
        }
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
